import copy
import traceback

from handlers.lib_handlers import necessary_params_check, optional_params_check, list_in_list_to_dict_in_list, \
    get_city_name
from handlers.user_show import generate_token
from submodules.common.lib.log_ import logger
from lib import http

from tools import mysql_

db_name = "house_information"
table_name = "old_house"
column_names = ['id', 'city_id', 'alias', 'neiborhood_id', 'pricing_persqm', 'pricing_sum', 'floor_number',
                'floor_squaremeter',
                'listing_time', 'toward', 'room_type', 'elevator', 'property_type', 'decoration_type', 'address',
                'agency_name', 'sale_status', 'source_type', 'created_at', 'updated_at', 'status']


def old_house_create(req):
    try:
        necessary_param_list = ["neiborhood_id"]
        res = http.Response()
        body = req.body

        if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
                                              res=res)) == True:
            pass
        else:
            res = res_tmp
            return res.__dict__

        key_list, value_list = [], []
        for k, v in body.items():
            key_list.append(k)
            value_list.append(v)
        value_list_with_quotes = ['"' + str(x) + '"' for x in value_list]
        sql = f'''INSERT INTO {db_name}.{table_name} ({",".join(key_list)}) VALUES ({",".join(value_list_with_quotes)});'''
        logger.info(sql)
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def old_house_update_status(req):
    try:
        necessary_param_list = ["id", "status"]
        res = http.Response()
        body = req.body

        # 参数校验
        if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
                                              res=res)) == True:
            pass
        else:
            res = res_tmp
            return res.__dict__

        # 拼接sql
        id = body["id"]
        status = body["status"]

        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET status = '{status}' where id = '{id}';'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def old_house_modify(req):
    try:
        optional_param_list = ["id", "pricing_persqm", "address", "agency_name", "alias", "city_id"]
        res = http.Response()
        body = req.body
        body.__delitem__("city_name")
        dict_tmp = copy.copy(body)
        for k, v in body.items():
            if str(v).strip() == "" or str(v).strip() == "None":
                dict_tmp.__delitem__(k)
        body = dict_tmp

        # 参数校验
        # if (res_tmp := optional_params_check(optional_param_list=optional_param_list, type="body", req=req,
        #                                      res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        id = body["id"]
        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET {",".join(optional_sql_str_list)} where id = {id};'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc(e))
        return res.__dict__


ERRNO_PASSWORD_WRONG = 0
ERRNO_INTERNAL_ERROR = 0
ERRMSG_INTERNAL_ERROR = 0
ERRMSG_PASSWORD_WRONG = 0
ERRNO_DB_ERROR = 0
ERRMSG_DB_ERROR = 0
ERRNO_SUCCESS = 0
ERRMSG_SUCCESS = 0


def old_house_modify(req):
    try:
        # 定义可选参数
        opl = ["id", "city_id", "neiborhood_id", "alias", "status"]
        # 创建返回对象
        res = http.Response()
        # 参数校验
        if (res_tmp := optional_params_check(opl, req=req, res=res)) == True:
            pass
        else:
            res = res_tmp
            return res.__dict__
        # 更新数据
        body = req.body
        res_db = mysql_.update(db_name, table_name, conditions=body)
        # 返回结果
        if res_db.stauts == 0:
            res.code = ERRNO_SUCCESS
            res.msg = ERRMSG_SUCCESS
            return res.__dict__
        else:
            res.code = ERRNO_DB_ERROR
            res.msg = ERRMSG_DB_ERROR
            return res.__dict__
    except Exception as e:
        # 异常处理
        res.code = ERRNO_INTERNAL_ERROR
        res.msg = ERRMSG_INTERNAL_ERROR
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


if __name__ == "__main__":
    from lib.http import Request


    def test_old_house_create():
        req = Request()
        req.body = {
            "alias": "3室2厅 云山悦",
            "neiborhood_id": "123456",
            "pricing_persqm": "10000"
        }
        res = old_house_create(req)
        print(res)


    def test_old_house_update_status():
        req = Request()
        req.body = {
            "id": "1",
            "status": "2"
        }
        res = old_house_update_status(req)
        print(res)


    def test_old_house_modify():
        req = Request()
        req.body = {
            "id": "1",
            "pricing_persqm": "20000"
        }
        res = old_house_modify(req)
        print(res)


    def test_old_house_list():
        req = Request()
        req.body = {
        }
        res = old_house_list(req)
        print(res)


    # test_old_house_create()
    # test_old_house_update_status()
    # test_old_house_modify()
    test_old_house_list()
